<?php
/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */

	//database handler is being used for session on admin panel
	if(defined('MF_DB_NAME')){
		//uses db handler
		$session = new DatabaseSessionHandler();
		$session->setDbDetails();

		$session->setDbTable(MF_TABLE_PREFIX .'sessions');
		session_set_save_handler($session);

		// The following prevents unexpected effects when using objects as save handlers.
		register_shutdown_function('session_write_close');
	}

	//check if HTTPS enabled or not
	$is_https_enabled = false;
	if(!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')){
		$is_https_enabled = true;
	}else if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'){
		$is_https_enabled = true;
	}else if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && $_SERVER['HTTP_FRONT_END_HTTPS'] == 'on'){
		$is_https_enabled = true;
	}

	//prevent CSRF
	if($is_https_enabled){
		if(PHP_VERSION_ID < 70300) {
			//for PHP version 7.2
			session_set_cookie_params(0, '/; samesite=Lax; Secure');
		}else{
			//for PHP version 7.3 or newer
			ini_set('session.cookie_samesite', 'Lax');
			ini_set('session.cookie_secure', true);
		}
	}
	session_start();

	//enforce session expiry based on session.gc_maxlifetime
	$session_max_life = ini_get("session.gc_maxlifetime");
	$session_life = time() - ($_SESSION['session_timeout'] ?? time());

	if ($session_life > $session_max_life) {
		session_destroy();

		$current_dir = dirname($_SERVER['PHP_SELF']);
      	if($current_dir == "/" || $current_dir == "\\"){
			$current_dir = '';
		}

		header("Location: ".$current_dir.'/index.php?from='.base64_encode($_SERVER['REQUEST_URI']).'&relogin=1');
		exit;
	}

	$_SESSION['session_timeout'] = time();
	
	date_default_timezone_set(@date_default_timezone_get());	
	error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

	@header("Content-Type: text/html; charset=UTF-8");

